package com.gange.filter;

import com.gange.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//表示该过滤器过滤所有的请求。
@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
    //初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    //销毁方法
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
    //每次请求控制器都会进入doFilter方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("-------w我是过滤器--------");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURL().toString();
        if(!url.endsWith("/login")) {
            String token = request.getHeader("token");
            try {
                JwtUtils.parseJWT(token);
            }catch (Exception e){
                e.printStackTrace();
                //响应错误信息
                HttpServletResponse response = (HttpServletResponse)servletResponse;
                response.setContentType("application/json");
                String json = "{\n" +
                        "\t\"code\": 0,\n" +
                        "\t\"msg\": \"NOT_LOGIN\",\n" +
                        "\t\"data\": null\n" +
                        "}";
                response.getWriter().print(json);
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
